<template>
  <div>
    <div v-if="loading" style="text-align:center; height: 100%; height:400px;">
      <i class="el-icon-loading"></i> 词云加载中...
    </div>
    <div v-else
         id="wordcloud"
         ref="wordcloud"
         style="width: 100%; height: 400px;"
         @click="handleChartClick">
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts-wordcloud';
import { ReadCloudHdfs } from "@/api/job";

export default {
  name: 'PlotWordCloud',
  data() {
    return {
      loading: true,
      words: [],
      chart: null,
      selectedWord: null,
      // colorPalette: [
      //   '#c4ccd3', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
      //   '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570',
      //   '#c23531', '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9',
      //   '#ea7e53', '#eedd78', '#73a373', '#73b9bc', '#7289ab'
      // ]
    };
  },
  async mounted() {
    try {
      const res = await ReadCloudHdfs();
      this.words = res.data.data || [];

      // 对词频进行归一化处理，增强大小差异
      this.normalizeWordFrequencies();

      this.loading = false;
      await this.$nextTick();
      this.initChart();
    } catch (error) {
      console.error('读取词云数据失败:', error);
      this.loading = false;
    }
  },
  methods: {
    normalizeWordFrequencies() {
      if (this.words.length === 0) return;

      const frequencies = this.words.map(item => item.frequency);
      const maxFreq = Math.max(...frequencies);
      const minFreq = Math.min(...frequencies);

      // 使用对数缩放增强小值的区分度
      this.words.forEach(item => {
        item.normalizedValue = Math.log(item.frequency - minFreq + 1) /
            Math.log(maxFreq - minFreq + 1) * 100;
      });
    },

    initChart() {
      this.chart = echarts.init(this.$refs.wordcloud);

      const option = {
        // backgroundColor: '#424242',
        // backgroundColor: 'rgba(0, 0, 0, 2)', // 设置背景颜色为透明
        title: {
          left: 'center',
          top: 10,
          textStyle: {
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          show: true,
          formatter: params => {
            return `<div style="font-size:14px;color:#f8f9fa;font-weight:bold">
                      ${params.name}<br/>
                      出现频率: ${params.value}
                    </div>`;
          }
        },
        series: [{
          type: 'wordCloud',
          shape: 'circle',
          sizeRange: [14, 60],  // 调整大小范围
          rotationRange: [-45, 45],  // 减少旋转角度范围
          rotationStep: 15,
          gridSize: 6,  // 更小的网格大小使布局更紧凑
          drawOutOfBound: false,
          textStyle: {
            fontFamily: 'Microsoft YaHei, sans-serif',
            fontWeight: 'bold',
            // color: (params) => {
            //   // 使用预设的调色板
            //   return this.colorPalette[params.dataIndex % this.colorPalette.length];
            // }
            color: '#f8f9fa', // 设置所有单词的颜色
          },
          emphasis: {
            focus: 'self',
            textStyle: {
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          data: this.words.map(item => ({
            name: item.word,
            value: item.normalizedValue || item.frequency,
            // itemStyle: {
            //   color: this.colorPalette[Math.floor(Math.random() * this.colorPalette.length)]
            // }
            // itemStyle: {
            //   color: this.colorPalette[index % this.colorPalette.length], // 根据调色板设置每个单词的颜色
            // }            , // 设置所有单词的颜色
            temStyle: {
              color: '#f8f9fa'
               }
          }))
        }]
      };

      this.chart.setOption(option);

      // 添加窗口大小变化监听
      window.addEventListener('resize', this.handleResize);

      // 添加点击事件
      this.chart.on('click', params => {
        this.selectedWord = params.name;
        this.$emit('word-click', params.name);
      });
    },

    handleChartClick() {
      if (this.selectedWord) {
        console.log(`当前选中: ${this.selectedWord}`);
        // 可以在这里添加自定义点击逻辑
      }
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      window.removeEventListener('resize', this.handleResize);
    }
  }
};
</script>

<style >
#wordcloud {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 900px;
}
</style>


